package com.zjx.shop.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.zjx.shop.search.config.GulimallElasticSearchConfig;
import com.zjx.shop.search.constant.EsConstant;
import com.zjx.shop.common.entity.SkuEsModel;
import com.zjx.shop.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 郑家莽
 */
@Service("productSaveServiceImpl")
@Slf4j
public class ProductSaveServiceImpl implements ProductSaveService {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {
        // 保存到es中
        //1、给es中建立索引。product，建立好映射关系。
        //2、给es中保存这些数据
        //BulkRequest bulkRequest, RequestOptions options
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel model : skuEsModels) {
            // 构造保存请求
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            //指定数据id
            indexRequest.id(model.getSkuId().toString());
            //将要保存的数据对象转换为JSON格式
            String s = JSON.toJSONString(model);
            //插入数据 并指明数据类型为JSON
            indexRequest.source(s, XContentType.JSON);
            //将保存请求(indexRequest)添加到批量保存请求中
            bulkRequest.add(indexRequest);
        }
        //创建批量执行对象
        //使用restHighLevelClient客户端进行保存 拿到响应结果
        //两个参数 第一个是批量保存的请求 第二个是请求OPTIONS
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);

        //分析保存结果
        boolean b = bulk.hasFailures();
        if (b)
        {
            return b;
        }else {
            List<String> collect = Arrays.stream(bulk.getItems()).map(item -> {
                return item.getId();
            }).collect(Collectors.toList());
            log.info("商品上架成功: {}", collect);
            return b;
        }
    }
}

